package cn.android.support.v7.lib.sin.crown.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;


import cn.android.support.v7.lib.sin.crown.utils.AssetsUtils;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;

/**
 * 标签适配View,子View可以自定义宽度。一行放不下了。才会自动换行。
 * 使用：
 * labelsView.addMyTextView("坚实的");//添加文本
 * labelsView.requestLayout();//重新布局
 * Created by 彭治铭 on 2018/1/17.
 */

public class LabelsView extends ViewGroup {
    public LabelsView(Context context) {
        super(context);
        init();
    }

    public LabelsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    interface OnClickCallBackListener {
        abstract void onclick(int index, String text);
    }

    OnClickCallBackListener onClickCallBackListener;//点击事件回调。返回当前item的下标和文本信息。

    //设置点击回调事件
    public void setOnClickCallBackListener(OnClickCallBackListener onClickCallBackListener) {
        this.onClickCallBackListener = onClickCallBackListener;
    }

    int width = (int) ProportionUtils.getInstance().realWidthPixels;//宽度,默认全屏。
    int height = ProportionUtils.getInstance().adapterInt(0);//高度。可以不用管。会自己测量出来的。自适应的。

    //设定当前ViewGroup的宽度。高度不用设定。高度是自适应高度。会自动计算出来。
    public void setWidthAndHeight(int width) {
        if (width > 0) {
            this.width = ProportionUtils.getInstance().adapterInt(width);
            requestLayout();
        }
    }

    Bitmap selectBitmap;//文本选中时，显示的打钩图片。

    public LabelsView setSelectBitmap(Bitmap selectBitmap) {
        this.selectBitmap = selectBitmap;
        return this;
    }

    boolean isDouble = false;//是否支持多选。true支持，false不支持。

    public LabelsView setDouble(boolean aDouble) {
        isDouble = aDouble;
        return this;
    }

    private int currentIndex;//当前选中下标，单选模式下有效

    public int getCurrentIndex() {
        return currentIndex;
    }

    public void setCurrentIndex(int currentIndex) {
        if (!isDouble) {
            //不是多选模式。先全部恢复不选中状态。再对特定的进行选中。
            this.currentIndex = currentIndex;
            for (int i = 0; i < getChildCount(); i++) {
                MyTextView myTextView = (MyTextView) getChildAt(i);
                if (myTextView.getIndex() == currentIndex) {
                    myTextView.setState(!myTextView.isState());
                } else {
                    myTextView.setState(false);
                }
                myTextView.invalidate();
            }
            invalidate();
        }
    }

    public int defaultTextColor = Color.parseColor("#414141");//默认字体颜色。
    public int selectTextColor = Color.parseColor("#E36A93");//选中字体颜色。


    public LabelsView setTextColor(int defaultTextColor, int selectTextColor) {
        this.selectTextColor = selectTextColor;
        this.defaultTextColor = defaultTextColor;
        return this;
    }

    public int defaultTextSize = ProportionUtils.getInstance().adapterInt(25);//默认，字体大小。
    public int selectTextSize = defaultTextSize;//选中字体大小。

    public LabelsView setTextSize(int defaultTextSize, int selectTextSize) {
        this.defaultTextColor = defaultTextColor;
        this.selectTextColor = selectTextSize;
        return this;
    }

    private void init() {
        selectBitmap = AssetsUtils.getInstance().getBitmapFromAssets( "crown/icon/correct.png", 0, true);
        int w = ProportionUtils.getInstance().adapterInt(30);
        selectBitmap = Bitmap.createScaledBitmap(selectBitmap, w, w, true);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(width, height);
    }

    int leftOffset = ProportionUtils.getInstance().adapterInt(24);
    int topOffset = leftOffset;


    //测量子View的x，y坐标。
    public void measureLayout() {
        int x = 0 + leftOffset;
        int x2;
        int y;
        int line = 1;//记录第几行
        for (int i = 0; i < getChildCount(); i++) {
            MyTextView myTextView = (MyTextView) getChildAt(i);
            if ((x + myTextView.getmWidth()) > (width + leftOffset)) {
                x = leftOffset;
                line++;//换行
            }
            x2 = x + myTextView.getmWidth();
            y = myTextView.getmHeight() * (line - 1) + topOffset * line;
            height = y + myTextView.getmHeight() + topOffset;//自动计算出最大高度
            //Log.e("test", "行数:\t" + line + "\t高度:\t" + height);
            myTextView.setX(x);//设置子控件View的x,y位置。
            myTextView.setY(y);
            myTextView.setIndex(i);//设定当前子View的下标
            x = x2 + leftOffset;
        }
    }

    //重写requestLayout();
    @Override
    public void requestLayout() {
        measureLayout();//对子View先进行测量。然后子啊布局。
        super.requestLayout();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        for (int i = 0; i < getChildCount(); i++) {
            MyTextView myTextView = (MyTextView) getChildAt(i);
            myTextView.layout();
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (selectBitmap != null) {
            for (int i = 0; i < getChildCount(); i++) {
                MyTextView myTextView = (MyTextView) getChildAt(i);
                if (myTextView.isState()) {
                    int x = (int) (myTextView.getX() + myTextView.getmWidth() - selectBitmap.getWidth() / 2);
                    int y = (int) (myTextView.getY() + myTextView.getmHeight() - selectBitmap.getHeight() * 0.7);
                    canvas.drawBitmap(selectBitmap, x, y, paint);
                }
            }
        }
    }

    /**
     * @param text    设置文本
     * @param isstate 是否选中
     */
    public void addMyTextView(String text, boolean isstate) {
        MyTextView myTextView = new MyTextView(getContext());
        myTextView.setMyText(text);
        myTextView.setState(isstate);
        addView(myTextView);
    }

    public void addMyTextView(String text) {
        MyTextView myTextView = new MyTextView(getContext());
        myTextView.setMyText(text);
        addView(myTextView);
    }

    Paint paint = new Paint();
    public int radius = ProportionUtils.getInstance().adapterInt(15);//圆角半径
    public int defaultBackgroundColor = Color.parseColor("#E6E6E6");//默认时背景颜色
    public int selectBackgroundColor = Color.parseColor("#F9DEE7");//选中时的背景颜色

    public class MyTextView extends View implements OnClickListener {
        private int index = 0;//當前下標。viewGroup里面的数组下标。

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        private int x, y;//记录控件相对父容器的坐标。以左上角为标准


        public void setX(int x) {
            this.x = x;
        }

        public void setY(int y) {
            this.y = y;
        }

        public boolean state = false;//是否选中。

        public boolean isState() {
            return state;
        }

        public void setState(boolean state) {
            this.state = state;
        }

        public MyTextView(Context context) {
            super(context);
            init();
        }

        public MyTextView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            init();
        }

        int leftPadding;

        private void init() {
            leftPadding = ProportionUtils.getInstance().adapterInt(16);
            setOnClickListener(this);//自动添加点击事件
        }

        int mWidth;//文本的宽度
        int mHeight = ProportionUtils.getInstance().adapterInt(55);//文本的高度
        int maxWidth = ProportionUtils.getInstance().adapterInt(137);//文本的最大宽度

        public int getmWidth() {
            return mWidth;
        }

        public int getmHeight() {
            return mHeight;
        }

        String text;

        //设置文本,在设置文本的同时。动态获取宽和高
        public void setMyText(String text) {
            if (state) {
                paint.setTextSize(selectTextSize);
            } else {
                paint.setTextSize(defaultTextSize);
            }
            mWidth = 0;
            if (text != null) {
                String s = text.toString().trim();
                int w = (int) paint.measureText(s, 0, s.length());
                mWidth = mWidth + w;
                if (mWidth > maxWidth) {
                    mWidth = maxWidth;
                    if (text.length() > 5) {
                        text = text.substring(0, 5) + "...";//多余五个文字的用点点点显示。
                    }
                }
                mWidth = mWidth + leftPadding * 2;//加上内补丁,根据文本自动计算出控件的宽度
            }
            this.text = text;
        }

        //设定布局位置
        public void layout() {
            layout(x, y, x + mWidth, y + height);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            if (state) {
                //选中样式
                paint.setColor(selectBackgroundColor);
            } else {
                //未选中样式
                paint.setColor(defaultBackgroundColor);
            }
            Path path = new Path();
            path.addRoundRect(new RectF(0, 0, mWidth, mHeight), radius, radius, Path.Direction.CCW);//设置圆角背景
            canvas.drawPath(path, paint);
            //要放到最后，不会文字就被遮挡看不到了。
            if (text != null) {
                if (state) {
                    paint.setColor(selectTextColor);
                } else {
                    paint.setColor(defaultTextColor);
                }
                paint.setTextAlign(Paint.Align.CENTER);
                canvas.drawText(text, mWidth / 2, (float) (mHeight * 0.68), paint);
            }
        }

        //自动添加点击事件
        @Override
        public void onClick(View v) {
            setCurrentIndex(getIndex());
            if (onClickCallBackListener != null) {
                onClickCallBackListener.onclick(index, text);
            }
        }
    }

}
